package com.gs.SynPatrolRep.fragment;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gs.SynPatrolRep.R;
import com.gs.SynPatrolRep.activity.event.CreateReportActivity;
import com.gs.SynPatrolRep.activity.palBill.PalBillItemActivity;
import com.gs.SynPatrolRep.adapter.PalBillEventAdapter;
import com.gs.SynPatrolRep.adapter.PalBillSiteAdapter;
import com.gs.SynPatrolRep.adapter.base.BaseAdapter;
import com.gs.SynPatrolRep.apiresult.ApiResultData;
import com.gs.SynPatrolRep.apiresult.PagedList;
import com.gs.SynPatrolRep.constant.AllConstants;
import com.gs.SynPatrolRep.constant.EventCode;
import com.gs.SynPatrolRep.db.bean.Event;
import com.gs.SynPatrolRep.db.dto.CreatePalBillEventResultDto;
import com.gs.SynPatrolRep.db.dto.PalBillEventDto;
import com.gs.SynPatrolRep.db.dto.PalBillSiteDto;
import com.gs.SynPatrolRep.db.query.PalBillSiteListQuery;
import com.gs.SynPatrolRep.dialog.ComboPicDialog;
import com.gs.SynPatrolRep.dialog.LoadingDialogUtils;
import com.gs.SynPatrolRep.dialog.ReportResultDialog;
import com.gs.SynPatrolRep.dialog.ToastDialogUtils;
import com.gs.SynPatrolRep.fragment.base.BaseListFragment;
import com.gs.SynPatrolRep.presenter.PalBillSiteListPresenter;
import com.gs.SynPatrolRep.util.NfcUtils;
import com.gs.SynPatrolRep.util.PermissionUtil;
import com.gs.SynPatrolRep.view.IPalBillSiteListView;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

public class PalBillSiteFragment extends BaseListFragment<IPalBillSiteListView, PalBillSiteListPresenter, PalBillSiteDto, PalBillSiteListQuery>
        implements IPalBillSiteListView {

    private PalBillSiteAdapter adapter;
    private int what;
    private String id,eventId;
    private PalBillSiteDto selBean;
    private List<PalBillEventDto> listEvent;
    private PalBillEventAdapter adapterEvent;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_inspection_list;
    }

    @Override
    protected PalBillSiteListPresenter createPresenter() {
        return new PalBillSiteListPresenter();
    }

    @Override
    protected PalBillSiteListQuery createQuery() {
        return new PalBillSiteListQuery();
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        final Bundle bundle = getArguments();
        if (bundle != null) {
            what = bundle.getInt(AllConstants.WHAT);
            id = bundle.getString(AllConstants.ID);
        }
        recyclerView.setLayoutManager(new LinearLayoutManager(context, RecyclerView.VERTICAL, false));
        if (what == 3) {
            listEvent = new ArrayList<>();
            adapterEvent = new PalBillEventAdapter(context, listEvent, R.layout.rvitem_event);
            adapterEvent.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
                @Override
                public void onItemClickListener(View v, int position) {
                    PalBillEventDto dto = listEvent.get(position);
                    if (dto.getPro() == 0) {
                        eventId = dto.getId();
                        mPresenter.getData(eventId);
                    }else {
                        Intent intent = new Intent(context, CreateReportActivity.class);
                        intent.putExtra(AllConstants.ID,dto.getId());
                        intent.putExtra(AllConstants.INFO_TYPE,3);
                        startActivity(intent);
                    }
                }
            });
            recyclerView.setAdapter(adapterEvent);
        } else {
            adapter = new PalBillSiteAdapter(context, list, R.layout.rvitem_inspection_list, what);
            if (what == 0) {
                adapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClickListener(View v, int position) {
                        selBean = list.get(position);
                        adapter.changeSelect(position);
                        if (selBean.getLblType() == null) {
                            ToastDialogUtils.getInstance().showInfoMessage(context, R.string.site_error);
                            return;
                        }
                        switch (selBean.getLblType()) {
                            // 二維碼
                            case 1:
//                            Intent intent = new Intent(context, PalBillItemActivity.class);
//                            Bundle bundle1 = new Bundle();
//                            bundle1.putString(AllConstants.ID, id);
//                            bundle1.putString(AllConstants.NAME, selBean.getSiteName());
//                            bundle1.putString(AllConstants.WHAT, selBean.getSiteId());
//                            intent.putExtra(AllConstants.WHAT, bundle1);
//                            startActivityForResult(intent, 1);
                                if (PermissionUtil.addPermission(getActivity(),
                                        new String[]{Manifest.permission.CAMERA},
                                        ComboPicDialog.PIC_CAREMA)) {
                                    Intent intent = new Intent(context, CaptureActivity.class);
                                    startActivityForResult(intent, 2);
                                }
                                break;
                            // 藍牙
                            case 2:

                                break;
                            // NFC
                            case 3:
                                NfcUtils nfcUtils = new NfcUtils(getActivity());
                                if (NfcUtils.mAdapter != null) {
                                    NfcUtils.mAdapter.enableForegroundDispatch(getActivity(), NfcUtils.mPendingIntent, NfcUtils.mIntentFilter, NfcUtils.mTechList);
                                }
                                break;
                        }
                    }
                });
            }
            recyclerView.setAdapter(adapter);
        }
    }

    @Override
    protected void loadData() {
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(Event event) {
        String msg = event.getMessage();
        switch (event.getWhat()) {
            case EventCode.EVENT_SITE_ITEM:
                if (what == 3) {
                    listEvent.clear();
                    listEvent.addAll(event.getEvents());
                    adapterEvent.notifyDataSetChanged();
                } else {
                    list.clear();
                    if (what == 2) {
                        list.addAll(event.getSites());
                    } else {
                        for (PalBillSiteDto bean : event.getSites()) {
                            if (bean.getCurState() == what) {
                                list.add(bean);
                            }
                        }
                    }
                    adapter.notifyDataSetChanged();
                }
                break;
            case EventCode.EVENT_SITE_SEARCH:
                if (event.getCurPos() == what) {
                    list.clear();
                    query.setKeyWord(msg);
                    mPresenter.getData(query);
                }
                break;
            case EventCode.EVENT_SCAN:
                if (what == 0) {
                    if (selBean == null) {
                        ToastDialogUtils.getInstance().showInfoMessage(context, R.string.unselect);
                        return;
                    }
                    jump(msg, R.string.error_site);
                }
                break;
            case EventCode.EVENT_NFC:
                if (what == 0) {
                    if (selBean == null) {
                        return;
                    }
                    jump(msg + selBean.getSiteId(), R.string.error_nfc_site);
                }
                break;
        }
    }

    private void jump(String msg, int error) {
        if (selBean.getLblTypeContent().equals(msg)) {
            Intent intent = new Intent(context, PalBillItemActivity.class);
            Bundle bundle1 = new Bundle();
            bundle1.putString(AllConstants.ID, id);
            bundle1.putString(AllConstants.NAME, selBean.getSiteName());
            bundle1.putString(AllConstants.WHAT, selBean.getSiteId());
            intent.putExtra(AllConstants.WHAT, bundle1);
            startActivityForResult(intent, 1);
            selBean = null;
        } else {
            ToastDialogUtils.getInstance().showInfoMessage(context, error);
        }
    }

    @Override
    protected void search() {
    }

    private void getData() {
        EventBus.getDefault().post(new Event(EventCode.EVENT_SITE_REFRESH));
    }

    @Override
    public void filter() {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            getData();
        } else if (requestCode == 2) {
            if (data == null) {
                return;
            }
            Bundle bundle = data.getExtras();
            if (bundle == null) {
                return;
            }
            if (selBean == null) {
                ToastDialogUtils.getInstance().showInfoMessage(context, R.string.unselect);
                return;
            }
            if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                String msg = bundle.getString(CodeUtils.RESULT_STRING);
                jump(msg, R.string.error_site);
            }
        }
    }

    @Override
    public void onGetDataSuccess(ApiResultData<PagedList<PalBillSiteDto>> apiResultData) {
        refreshSmartRefreshLayout();
        if (apiResultData.getStatus() != 2000) {
            Toast.makeText(context, apiResultData.getMessage(), Toast.LENGTH_LONG).show();
            adapter.notifyDataSetChanged();
            return;
        }
        list.addAll(apiResultData.getData().getList());
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onGetDataFails(Exception e) {
        refreshSmartRefreshLayout();
        adapter.notifyDataSetChanged();
        Toast.makeText(context, R.string.network_error, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onGetDataIdSuccess(ApiResultData<PalBillEventDto> apiResultData) {
        if (apiResultData.getStatus() != 2000) {
            ToastDialogUtils.getInstance().showInfoMessage(context, apiResultData.getMessage());
            return;
        }
        PalBillEventDto dto = apiResultData.getData();
        new ReportResultDialog(context, dto.getEventNum(), dto.getPhotos(), new ReportResultDialog.IChoiceListener() {
            @Override
            public void getChoiceFromDialog(CreatePalBillEventResultDto bean) {
                bean.setId(eventId);
                mPresenter.setResult(bean);
            }
        }).show();
    }

    @Override
    public void onGetDataIdFail(Exception e) {
        ToastDialogUtils.getInstance().showInfoMessage(context, getString(R.string.network_error));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onSetResultSuccess(ApiResultData<String> apiResultData) {
        ToastDialogUtils.getInstance().showInfoMessage(context, apiResultData.getMessage());
        if (apiResultData.getStatus() == 2000) {
            getData();
        }
    }

    @Override
    public void onSetResultFail(Exception e) {
        ToastDialogUtils.getInstance().showInfoMessage(context, getString(R.string.network_error));
    }

    @Override
    public void showLoading() {
        LoadingDialogUtils.getInstance().showLoading(context);
    }

    @Override
    public void hideLoading() {
        LoadingDialogUtils.getInstance().dismiss();
    }
}
